package org.example.chrome;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriverService;

import com.google.common.collect.Lists;

public class ChromeUtils {
    public static final ChromeDriverService SERVICE;
    public static List<WebDriver> DRIVERS = Lists.newArrayList();

    static {
        SERVICE = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File("chromedriver115"))
                .usingAnyFreePort()
                .build();
        try {
            SERVICE.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static File create_proxyauth_extension(String host, String port, String username, String password) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);
        // 写入 background.js 文件
        InputStream is = ChromeUtils.class.getResourceAsStream("/background.js");
        String line = new String(is.readAllBytes());
        is.close();
        line = line.replace("YOU_PROXY_ADDRESS", host);
        line = line.replace("YOUR_PROXY_PORT", port);
        line = line.replace("YOUR_PROXY_USERNAME", username);
        line = line.replace("YOUR_PROXY_PASSWORD", password);
        zos.putNextEntry(new ZipEntry("background.js"));
        zos.write(line.getBytes());
        // 写入 manifest.json 文件
        is = ChromeUtils.class.getResourceAsStream("/manifest.json");
        zos.putNextEntry(new ZipEntry("manifest.json"));
        zos.write(is.readAllBytes());
        is.close();
        zos.flush();
        zos.close();

        File f = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
        fos.write(os.toByteArray());
        fos.close();
        return f;
    }
}
